var dispatcher = require('../../../util/dispatcher');

module.exports = function (app) {
	return new Handler(app);
};

var Handler = function (app) {
	this.app = app;
};

var handler = Handler.prototype;

/**
 * Gate handler that dispatch user to connectors.
 *
 * @param {Object} msg message from client
 * @param {Object} session
 * @param {Function} next next stemp callback
 *
 */
handler.loginConServer = function (msg, session, next) {
	var self = this;
	var room_id = msg.rid;
	var user_id = msg.username + "*" + room_id;
	var sesstionSevice = self.app.get('sessionService');

	// 检查重复登陆
	if(!! sesstionSevice.getByUid(user_id))
	{
		next(null, {
			code: 500
		});
		return;
	}


	session.bind(user_id);
	session.set('room_id', room_id);
	session.push('room_id', function (err) {
		if (err) {
			console.error('session.push error');
		}
	})

	session.on("closed", onUserLeave.bind(null, self.app)); //这里为什么要绑定， 原因是传一个参数，但是这里null?，并没有改变上下文啊，


	console.log("*****start rpc");
	self.app.rpc.chat.chatRemote.add(session, user_id, self.app.get('serverId'), room_id, true, function (users) {
		next(null, { users: users });
	});
};

var onUserLeave = function (app, session) {
	//判断下kick要传送的参数
	if( !session || !session.uid )
	{
		return;
	}
	app.rpc.chat.chatRemote.kick(session, session.uid, app.get('serverId'), session.get('room_id'), null);
}